package cn.mygweb.admin.modules.tools.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.mygweb.admin.modules.sys.pojo.Attachment;
import cn.mygweb.admin.modules.tools.pojo.Email;
import cn.mygweb.admin.modules.tools.pojo.EmailServerConf;
import cn.mygweb.common.controller.BaseController;
import cn.mygweb.common.pojo.JsonResult;
import cn.mygweb.common.utils.FileSizeUtil;
import cn.mygweb.common.utils.UploadUtils;
import lombok.extern.slf4j.Slf4j;

/** 
* <p>Title: EmailsController.java</p>
* <p>Description: 邮件管理控制层</p>  
* @author gxb 
* @date 2019年7月8日 
* <p>Copyright: Copyright (c) 2019</p>
* <p>Company: www.mygweb.cn</p> 
*/
@Controller
@RequestMapping("/admin")
@Slf4j
public class EmailsController extends BaseController{

	@Value("${pagehelper.pageSize}")
	private Integer pageSize;
	
	/**
	 * <p>Title: server</p>
	 * <p>Description: 访问邮件服务器配置页面</p>
	 * @return
	 */
	@RequestMapping("/settings/emails/conf")
	public String conf(ModelMap model) {
		List<EmailServerConf> escList = emailService.queryEmailConfList(new EmailServerConf());
		if(!super.isEmptyList(escList)) {
			model.addAttribute("emailServerConf", escList.get(0));
		}else {
			model.addAttribute("emailServerConf", new EmailServerConf());
		}
		return "admin/modules/settings/emailServerConf";
	}
	
	/**
	 * <p>Title: saveConf</p>
	 * <p>Description: 保存邮件服务器配置</p>
	 * @param emailServerConf
	 * @return
	 */
	@RequestMapping("/settings/emails/save")
	public String saveConf(EmailServerConf emailServerConf, String ssl) {
		if("on".equals(ssl)) {
			emailServerConf.setIsSsl(1);
		}else {
			emailServerConf.setIsSsl(0);
		}
		try {
			List<EmailServerConf> emailConfList = emailService.queryEmailConfList(new EmailServerConf());
			if(super.isEmptyList(emailConfList)) {
				if(null == emailServerConf.getPort() || "".equals(emailServerConf.getPort())) {
					emailServerConf.setPort(25);//如果端口为空则默认设置为25
				}
				emailServerConf.setId(sid.nextShort());
				emailService.saveEmailConf(emailServerConf);
			}else {
				if(null == emailServerConf.getPort() || "".equals(emailServerConf.getPort())) {
					emailServerConf.setPort(25);//如果端口为空则默认设置为25
				}
				emailService.updateEmailConf(emailServerConf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/admin/settings/emails/conf";
	}
	
	/**
	 * <p>Title: list</p>
	 * <p>Description: 访问邮件管理页面，分页显示已发送的邮件信息</p>
	 * @return
	 */
	@RequestMapping("/tools/emails/list")
	public String list(ModelMap model, Integer pageNum) {
		if(pageNum == null || pageNum < 1) {
			pageNum = 1;
		}
		Integer count = emailService.selectCount(new Email());
		model.addAttribute("count", count);//总记录条数
		
		Integer totalPages = count % pageSize == 0 ? (count / pageSize) : (count / pageSize + 1);
		model.addAttribute("totalPages", totalPages);//总页数
		
		if(pageNum > totalPages) {
			pageNum = totalPages;
		}
		model.addAttribute("currentPage", pageNum);//当前页
		
		List<Email> emailList = emailService.queryEmailListPaged(new Email(), pageNum, pageSize);
		model.addAttribute("emailList", emailList);
		return "admin/modules/tools/emails";
	}
	
	/**
	 * <p>Title: send</p>
	 * <p>Description: 发送邮件</p>
	 * @return
	 */
	@RequestMapping("/tools/emails/send")
	@ResponseBody
	public JsonResult send(Email email, @RequestParam("file") MultipartFile[] multipartFiles) {
		try {
			email.setId(sid.nextShort());
			email.setTime(new Date());
			
			List<String> idsList = new ArrayList<String>();
			List<String> attPathList = new ArrayList<String>();
			//先将附件上传，然后返回附件的路径存储到邮件中
			for (MultipartFile file : multipartFiles) {
				//String path = UploadUtils.uploadFile(file, uploadFilePath);
				String path = UploadUtils.uploadReturnRealPath(file, uploadFilePath, UploadUtils.ATTACHMENT);
				
				//存储附件信息
				Attachment att = getAttachment(file, path);				
				attachmentService.insert(att);
				
				idsList.add(att.getId());
				attPathList.add(path);
			}
			String attachmentIds = String.join(",", idsList);
			email.setAttachmentIds(attachmentIds);
			String attPaths = String.join(",", attPathList);
			
			EmailServerConf emailServerConf = emailService.queryEmailConfList(new EmailServerConf()).get(0);
			
			//此处需判断是使用发送附件的方法，还是发送图片的方法，还是发送html的方法
			if(super.isEmptyString(email.getAttachmentIds())) {//发送html
				emailService.sendMail(emailServerConf, email.getToUsername(), email.getSubject(), email.getContent(), null);
			}else {//发送带附件的内容
				emailService.sendMail(emailServerConf, email.getToUsername(), email.getSubject(),	email.getContent(), attPaths);
			}
			
			//将信息保存到数据库中
			emailService.saveEmail(email);
			
			log.info(email.getTime() + " 给 【" + email.getToUsername() + "】 发送邮件成功");
			return JsonResult.ok("发送成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(email.getTime() + " 给 【" + email.getToUsername() + "】 发送邮件失败");
			return JsonResult.errorMsg("发送失败");
		}
	}
	
	/**
	 * <p>Title: sendFromUserMng</p>
	 * <p>Description: 用户管理页面发送邮件</p>
	 * @param email
	 * @return
	 */
	@RequestMapping("/tools/emails/sendFromUserMng")
	public String sendFromUserMng(Email email) {
		try {
			EmailServerConf emailServerConf = emailService.queryEmailConfList(new EmailServerConf()).get(0);
			emailService.sendHtmlMail(emailServerConf, email.getToUsername(), email.getSubject(), email.getContent());
			//将信息保存到数据库中
			email.setId(sid.nextShort());
			email.setFromUsername(emailServerConf.getUsername());
			email.setTime(new Date());
			emailService.saveEmail(email);
			log.info(email.getTime() + " 给 【" + email.getToUsername() + "】 发送邮件成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(email.getTime() + " 给 【" + email.getToUsername() + "】 发送邮件失败");
		}
		return "redirect:/admin/sys/user/userList";
	}
	
	/**
	 * <p>Title: getAttachment</p>
	 * <p>Description: 获取附件对象信息</p>
	 * @param file
	 * @param path
	 * @return
	 */
	public Attachment getAttachment(MultipartFile file, String path) {
		Attachment att = new Attachment();
		att.setId(sid.nextShort());
		att.setOriginName(file.getOriginalFilename());
		String relativePath = UploadUtils.getRelativePath(path, uploadFilePath);
		att.setRelativePath(relativePath);
		att.setUploadPath(path);
		String fileSize = FileSizeUtil.formatFileSize(file.getSize());
		att.setFileSize(fileSize);
		att.setType(file.getContentType());
		att.setDownloadCounts(0);
		att.setUploadTime(new Date());
		return att;
	}
	
	/**
	 * 	接收邮件，参考地址：https://www.cnblogs.com/huangminwen/p/6096124.html
	 * 					  https://www.cnblogs.com/huangminwen/p/6107078.html
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		//收邮件demo
		String pop3Server = "imap.qq.com";
		String protocol = "imap";
		String username = "1246975590@qq.com";
		String password = "prqgfimnlsfbffgd";
		
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", protocol);
		props.setProperty("mail.smtp.host", pop3Server);
		
		Session session = Session.getDefaultInstance(props);
		session.setDebug(false);
		
		Store store = session.getStore(protocol);
		store.connect(pop3Server, username, password);
		
		Folder folder = store.getFolder("INBOX");
		folder.open(Folder.READ_WRITE);
		
		Message[] messages = folder.getMessages();
		System.out.println("邮件总数为："+messages.length);
		Thread.sleep(5000);
		
		for (Message message : messages) {
			String subject = message.getSubject();
			Address from = message.getFrom()[0];
			System.out.println("邮件主题为："+subject + "\t发件人地址为："+from);
			System.out.println("flag为："+message.getFlags());
			System.out.println("邮件内容为："+message.getContent());
			Thread.sleep(3000);
//			message.writeTo(System.out);
		}
		
		folder.close(false);
		store.close();
	}
	
}
